#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
日志设置模块
"""

import os
import logging
from logging.handlers import RotatingFileHandler
from pathlib import Path


def setup_logger(log_dir=None, log_level=logging.INFO):
    """设置日志记录器
    
    Args:
        log_dir: 日志目录，默认为./logs
        log_level: 日志级别，默认为INFO
    """
    if log_dir is None:
        log_dir = Path("./logs")
    else:
        log_dir = Path(log_dir)
    
    # 创建日志目录
    os.makedirs(log_dir, exist_ok=True)
    
    # 设置根日志记录器
    root_logger = logging.getLogger()
    root_logger.setLevel(log_level)
    
    # 清除现有处理器
    for handler in root_logger.handlers[::]:
        root_logger.removeHandler(handler)
    
    # 创建控制台处理器
    console_handler = logging.StreamHandler()
    console_handler.setLevel(log_level)
    console_format = logging.Formatter(
        "%(asctime)s - %(levelname)s - %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S"
    )
    console_handler.setFormatter(console_format)
    root_logger.addHandler(console_handler)
    
    # 创建文件处理器
    log_file = log_dir / "app.log"
    file_handler = RotatingFileHandler(
        log_file,
        maxBytes=10 * 1024 * 1024,  # 10MB
        backupCount=5,
        encoding="utf-8"
    )
    file_handler.setLevel(log_level)
    file_format = logging.Formatter(
        "%(asctime)s - %(levelname)s - %(name)s - %(filename)s:%(lineno)d - %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S"
    )
    file_handler.setFormatter(file_format)
    root_logger.addHandler(file_handler)
    
    logging.info(f"日志系统已初始化，日志文件: {log_file}")
    
    return root_logger


def get_logger(name):
    """获取指定名称的日志记录器
    
    Args:
        name: 日志记录器名称
        
    Returns:
        Logger: 日志记录器实例
    """
    return logging.getLogger(name)